package files

import (
	"bufio"
	"encoding/csv"
	"errors"
	"fmt"
	"github.com/mitchellh/go-homedir"
	"github.com/vrischmann/userdir"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
)

// GetExeDirIgnoreError SelfDir gets compiled executable file directory
func GetExeDirIgnoreError() string {
	return filepath.Dir(GetExePathIgnoreError())
}

// GetExePathIgnoreError 二进制文件所在目录
func GetExePathIgnoreError() string {
	exePath, err := os.Executable()
	if err != nil {
		println(err.Error())
	}
	return exePath
}

// GetRunPathIgnoreError 执行(启动)二进制文件的目录
func GetRunPathIgnoreError() string {
	path, err := os.Getwd()
	if err != nil {
		println(err.Error())
	}
	return path
}

func GetHomeDir() string {
	dir, err := homedir.Dir()
	if err != nil {
		println(err.Error())
	}
	return dir
}

func ExpandHomeDir(dir string) string {
	//dir = "~/golang/src"
	expandedDir, err := homedir.Expand(dir)
	if err != nil {
		println(err.Error())
	}
	fmt.Printf("Expand of %s is: %sn", dir, expandedDir)
	return expandedDir
}

func GetConfigHome() string {
	return userdir.GetConfigHome()
}

func GetDataHome() string {
	return userdir.GetDataHome()
}

func GetMacAppDir(appName string) string {
	homedir := GetHomeDir()
	datadir := filepath.Join(homedir, "/Library/Containers/"+appName)
	MkDirsWithParents(datadir)
	return datadir
}

// FileExists 判断文件存在
func FileExists(file string) bool {
	_, err := os.Stat(file)
	return err == nil || os.IsExist(err)
}

// FileIsDir 判断路径是否是文件夹
func IsDir(file string) bool {
	f, err := os.Stat(file)
	if err != nil {
		return false
	}
	return f.IsDir()
}

func CreateFileIfNotExist(filePath string) error {
	// 1. 判断文件是否存在
	_, err := os.Stat(filePath)
	if err == nil {
		// 文件已存在，直接返回
		return nil
	}

	// 2. 若文件不存在，先创建父目录（递归创建，确保所有层级目录存在）
	dir := filepath.Dir(filePath)                  // 获取文件所在的目录路径（如 "conf"）
	if err := os.MkdirAll(dir, 0755); err != nil { // 0755 是目录权限（rwxr-xr-x）
		return err // 目录创建失败
	}

	// 3. 创建文件（若文件已存在，Create 会截断文件；此处因已判断不存在，直接创建）
	file, err := os.Create(filePath)
	if err != nil {
		return err // 文件创建失败
	}
	defer file.Close() // 关闭文件句柄
	return nil         // 所有操作成功
}

// MkDirsWithParents 创建文件目录
func MkDirsWithParents(folderPath string) error {
	return os.MkdirAll(folderPath, 0777)
}

// SearchFile Search a file in paths.
// this is often used in search config file in /etc ~/
func SearchFile(filename string, paths ...string) (fullpath string, err error) {
	for _, path := range paths {
		if fullpath = filepath.Join(path, filename); FileExists(fullpath) {
			return
		}
	}
	err = errors.New(fullpath + " not found in paths")
	return
}

// ReadFile 读取文件
func ReadFile(filePath string) (string, error) {
	body, err := ioutil.ReadFile(filePath)
	return string(body), err
}

func ReadLines(filePath string) ([]string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	var lines []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	return lines, scanner.Err()
}

// WriteFile 写入文件
func WriteFile(filePath string, data string) error {
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("文件打开失败", err)
	}
	//及时关闭file句柄
	defer file.Close()

	//写入文件时，使用带缓存的 *Writer
	write := bufio.NewWriter(file)
	write.WriteString(data)
	//Flush将缓存的文件真正写入到文件中
	write.Flush()
	return nil
}

func IsRegularFile(fi os.FileInfo) bool {
	return fi.Mode()&(os.ModeDir|os.ModeSymlink|os.ModeNamedPipe|os.ModeSocket|os.ModeDevice) == 0
}

// GrepFile like command grep -E
// for example: GrepFile(`^hello`, "hello.txt") is striped while read
func GrepFile(patten string, filename string) (lines []string, err error) {
	re, err := regexp.Compile(patten)
	if err != nil {
		return
	}

	fd, err := os.Open(filename)
	if err != nil {
		return
	}
	lines = make([]string, 0)
	reader := bufio.NewReader(fd)
	prefix := ""
	isLongLine := false
	for {
		byteLine, isPrefix, er := reader.ReadLine()
		if er != nil && er != io.EOF {
			return nil, er
		}
		if er == io.EOF {
			break
		}
		line := string(byteLine)
		if isPrefix {
			prefix += line
			continue
		} else {
			isLongLine = true
		}

		line = prefix + line
		if isLongLine {
			prefix = ""
		}
		if re.MatchString(line) {
			lines = append(lines, line)
		}
	}
	return lines, nil
}

// SplitFileByPartNum 按分块数分块
func SplitFileByPartNum(fileSize int64, chunkNum int) ([]FileChunk, error) {
	if chunkNum <= 0 || chunkNum > 10000 {
		return nil, errors.New("chunkNum invalid")
	}

	if int64(chunkNum) > fileSize {
		return nil, errors.New("oss: chunkNum invalid")
	}

	var chunks []FileChunk
	var chunk = FileChunk{}
	var chunkN = (int64)(chunkNum)
	for i := int64(0); i < chunkN; i++ {
		chunk.Number = int(i + 1)
		chunk.Offset = i * (fileSize / chunkN)
		if i == chunkN-1 {
			chunk.Size = fileSize/chunkN + fileSize%chunkN
		} else {
			chunk.Size = fileSize / chunkN
		}
		chunks = append(chunks, chunk)
	}

	return chunks, nil
}

func ReadCsv(filePath string) (records [][]string, err error) {
	f, err := os.Open(filePath) // 读取文件
	if err != nil {
		fmt.Println(err)
	}

	defer f.Close()
	fmt.Println(f.Name())

	reader := csv.NewReader(f)
	return reader.ReadAll() // 读取全部数据
}

type FileChunk struct {
	Number int   // Chunk number
	Offset int64 // Chunk offset
	Size   int64 // Chunk size.
}

// SplitFileByPartSize 按大小分块， 参考阿里云
func SplitFileByPartSize(fileSize int64, chunkSize int64) ([]FileChunk, error) {
	if chunkSize <= 0 {
		return nil, errors.New("chunkSize invalid")
	}

	if fileSize <= 0 {
		return nil, errors.New("fileSize invalid")
	}

	if chunkSize > fileSize {
		return nil, errors.New("chunkSize must less then fileSize")
	}

	var chunkN = fileSize / chunkSize
	if chunkN >= 10000 {
		return nil, errors.New("Too many parts, please increase part size ")
	}

	var chunks []FileChunk
	var chunk = FileChunk{}
	for i := int64(0); i < chunkN; i++ {
		chunk.Number = int(i + 1)
		chunk.Offset = i * chunkSize
		chunk.Size = chunkSize
		chunks = append(chunks, chunk)
	}

	if fileSize%chunkSize > 0 {
		chunk.Number = len(chunks) + 1
		chunk.Offset = int64(len(chunks)) * chunkSize
		chunk.Size = fileSize % chunkSize
		chunks = append(chunks, chunk)
	}

	return chunks, nil
}
